<template>
    <div class="app-container bg-white">
        <div class="page-header flex align-center space-between border_bottom_1">
            <div class="font-weight--lg font-size--lg">{{title}}商品品牌</div>
        </div>
        <div class="page-body padding_15" v-loading="pageLoading">
            <el-form :model="brandForm" label-width="100px" size="small" class="form_box">
                <el-row :gutter="10">
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="品牌名称" required>
                        <el-input style="max-width: 320px" size="small" v-model.trim="brandForm.name" placeholder="请输入品牌名称" @input="watchInput($event, 'name')" maxlength="25" show-word-limit></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="brandId">
                    <el-form-item label="品牌编码">
                        <!-- onkeyup="value=value.replace(/[^\w\.\/]/ig,'')" -->
                        <el-input style="max-width: 320px" v-model.trim="brandForm.brandNo" placeholder="请输入品牌编码"  @input="inputSuppCode" maxlength="4" show-word-limit disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="品牌图片">
                        <app-uploader title="品牌图片" :limit="1" :initFiles="brandForm.images" :accept="'image/*'" :fileFormat="imgFileFormat" @change="imgSuccessOption($event)"></app-uploader>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="是否启用">
                        <el-switch size="small" v-model="brandForm.status"></el-switch>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="品牌资料包">
                        <app-uploader-zip title="资料包" :limit="1" :fileFormat="rarFileFormat" ref="uploadRef" @success="fileSuccessOption($event)">
                            <!-- <template slot="uploader">
                                <el-button>上传附件</el-button>
                            </template> -->
                        </app-uploader-zip>

                        <el-table max-height="480" stripe :data="pageData" :header-cell-style="tableHeaderStyle" v-loading="loading" class="margin_top_20" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="42"></el-table-column>
                            <el-table-column type="index" label="序号"></el-table-column>
                            <el-table-column prop="originalFilename" label="资料">
                                <template slot-scope="scope">
                                    <span class="text-brand">{{scope.row.originalFilename}}</span>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column prop="creatorId" label="上传人"></el-table-column>
                            <el-table-column prop="createTime" label="上传时间"></el-table-column> -->
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button size="mini" @click="fileDownload([baseUrl + scope.row.fileUrl])">下载</el-button>
                                    <el-button size="mini" type="danger" @click="fileRemove(scope.$index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="margin_top_10" v-show="pageData.length">
                            <el-button size="small" @click="allFileDownload()">下载</el-button>
                            <el-button size="small" type="danger" @click="allFileRemove()">删除</el-button>
                        </div>
                    </el-form-item>
                </el-col>
                </el-row>
            </el-form>
        </div>
      <div class="page-footer">
        <el-button @click="goBack()">取 消</el-button>
        <el-button type="primary" :loading="pageLoading" @click="submit()">确 定</el-button>
      </div>
    </div>
</template>

<script>
import Setting from '@/settings';
import AppUploader from '@/components/AppUploader/index';
import AppUploaderZip from '@/components/AppUploaderZip/index';
import { SaveStoreBrandItem, UpdateStoreBrandItem, GetStoreBrandDetail, GetGoodsZipList, InsertGoodsZipList, UpdateGoodsZipList } from '@/views/store-management/services/index';
export default {
    name: 'StoreAddOrEdit',
    components: {
        AppUploader,
        AppUploaderZip 
    },
    computed: {
        title() {
            return this.brandId ? '编辑' : '新建';
        }
    },
    data() {
        return {
            brandForm: {
                name: '',
                images: [],
                status: false,
                files: [],
                brandNo: ''
            },
            brandId: null,
            pageData: [],
            loading: false,
            pageLoading: false,
            imgFileFormat: ['jpg'],
            rarFileFormat: ['zip'],
            tableHeaderStyle: Setting.tableHeaderStyle,
            multipleSelection: [],
            baseUrl: process.env.VUE_APP_FILE_URL + '/'
        }
    },
    methods: {
        inputSuppCode(val) {
            val=val.replace(/[^\w\.\/]/ig,'');
            this.brandForm.brandNo = val.toUpperCase();
     },
        watchInput(event, key) {
            this.brandForm[key] = this.inputReplaceSpecialChar(event);
     },
        getZipList() {
        GetGoodsZipList({type: 2, id: this.brandId})
            .then(data => {
                if (data.code == 200) {
                    this.pageData = data.data.map(item => {
                        return {
                            originalFilename: item.originalFilename,
                            fileUrl: item.url
                        }
                    })
                }
            })
    },
        allFileRemove() {
            if (!this.multipleSelection || !this.multipleSelection.length) {
                this.$message.warning('请选择需要删除的资源包!');
                return;
            }
        else {
                 this.$confirm('此操作将永久删除该资料包, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                      const urlList = this.multipleSelection.map(item => item.fileUrl);
            this.pageData = this.pageData.filter(item => !urlList.includes(item.fileUrl));
                })
                .catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
        })
            }
        },
        fileRemove(index) {
            this.$confirm('此操作将永久删除该资料包, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                this.pageData.splice(index, 1);
                    this.$message.success('删除成功')
                })
                .catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
        })
        },
        allFileDownload() {
            if (!this.multipleSelection || !this.multipleSelection.length) {
                this.$message.warning('请选择需要下载的资源包!');
                return;
            }
            this.fileDownload(this.multipleSelection.map(item => this.baseUrl + item.fileUrl));
        },
        fileDownload(files) {
            this.filesDownload(files);
        },
        handleSelectionChange(selectlist) {
            this.multipleSelection = selectlist;
        },
        imgSuccessOption(event) {
            this.brandForm.images = event.map(item => item.fileUrl);
        },
        fileSuccessOption(event) {
            console.log(event)
            event.map(item => {
                this.pageData.unshift(item);
                }),
            console.log('this.pageData',this.pageData)
            this.$refs.uploadRef.fileList = [];
        },
        submit() {
            if (!this.brandForm.name) {
                this.$message.warning('请输入品牌名称!');
                return;
            }
            this.pageLoading = true;
            if (this.brandId) {
                UpdateStoreBrandItem({
                    id: this.brandId,
                    name: this.brandForm.name, // 品牌名称
                    brandNo:  this.brandForm.brandNo.toUpperCase(), //品牌编码
                    imgUrl: this.brandForm.images[0], // 品牌logo
                    status: this.brandForm.status ? 1 : 0, // 0下架，1上架
                    zips: this.pageData.map(item => {
                        return {
                            originalFilename: item.originalFilename,
                            url: item.fileUrl
                        }
                    })
                })
                .finally(() => this.pageLoading = false)
                .then(data => {
                    if (data.code == 200) {
                        this.$message.success('修改成功!');
                        this.goBack();
                    } else {
                        this.$message.error('修改失败!');
                    }
                })
                .catch(error => {
                    this.$message.error(error);
                })
            } else {
                SaveStoreBrandItem({
                    name: this.brandForm.name, // 品牌名称
                    brandNo:  this.brandForm.brandNo, //品牌编码
                    imgUrl: this.brandForm.images[0], // 品牌logo
                    status: this.brandForm.status ? 1 : 0, // 0下架，1上架
                    zips: this.pageData.map(item => {
                        return {
                            originalFilename: item.originalFilename,
                            url: item.fileUrl
                        }
                    })
                })
                .finally(() => this.pageLoading = false)
                .then(data => {
                    if (data.code == 200) {
                        this.$message.success('新建成功!');
                        this.goBack();
                    } else {
                        this.$message.error('新建失败!');
                    }
                })
                .catch(error => {
                    this.$message.error(error);
                })
            }
        },
        goBack() {
            this.$router.back();
        }
    },
    created() {
        if (this.$route.query.id) {
            this.brandId = this.$route.query.id;
            this.pageLoading = true;
            GetStoreBrandDetail({ id: this.brandId })
            .finally(() => this.pageLoading = false)
            .then(data => {
                if (data.code == 200) {
                    this.brandForm.name = data.data.name;
                    this.brandForm.brandNo = data.data.brandNo;
                    this.brandForm.images = [data.data.imgUrl];
                    this.brandForm.status = !!data.data.status;
                    
                } else {
                    this.$message.error('详情获取失败!');
                }
            })
            .catch(error => {
                this.$message.error(error);
            })
            
            GetGoodsZipList({type: 2, id: this.brandId})
            .then(data => {
                if (data.code == 200) {
                    this.pageData = data.data.map(item => {
                        return {
                            originalFilename: item.originalFilename,
                            fileUrl: item.url
                        }
                    })
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.form_box {
    max-width: 1064px;
    padding: 0;
    box-sizing: content-box;
}
</style>
